package com.example.windowdemo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.windowdemo.app.MyApp;
import com.example.windowdemo.bean.CallCleanBean;
import com.example.windowdemo.bean.CheckOutBean;
import com.example.windowdemo.callback.WindowAdapter;
import com.example.windowdemo.threadpool.WindowPool;
import com.example.windowdemo.threadpool.WindowThreadPool;
import com.example.windowdemo.utils.MMKVUtils;
import com.example.windowdemo.window.FloatingWindow;
import com.example.windowdemo.window.Window;
import com.example.windowdemo.window.WindowCreate;
import com.example.windowdemo.window.WindowShowManager;
import com.example.windowdemo.window.adapter.WindowBuilderAdapter;
import com.example.windowdemo.window.builder.WindowBuilder;
import com.example.windowdemo.window.component.WindowCustomComponent;
import com.example.windowdemo.window.composite.WindowComposite;
import com.example.windowdemo.window.decorator.WindowDecorator;
import com.example.windowdemo.window.factory.CustomWindowFactory;
import com.example.windowdemo.window.factory.WindowFactory;
import com.example.windowdemo.window.factory.WindowFactoryBuilder;
import com.example.windowdemo.window.flyweight.FlyweightWindow;
import com.example.windowdemo.window.flyweight.FlyweightWindowFactory;
import com.example.windowdemo.window.observer.WindowObserverManager;
import com.example.windowdemo.window.proxy.WindowProxy;
import com.example.windowdemo.window.single.WindowSingle;
import com.example.windowdemo.window.strategy.FullScreenWindowStrategy;
import com.example.windowdemo.window.strategy.StrategyWindow;
import com.example.windowdemo.window.strategy.WindowStrategyBuilder;
import com.example.windowdemo.window.templateWindow.MyTemplateWindow;
import com.example.windowdemo.window.vistor.WindowVisitor;
import com.example.windowdemo.window.vistor.WindowVisitorImpl;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private final List<Window> windows = new ArrayList<>();
    private WindowVisitorImpl visitor;
    private WindowVisitor<String> window;
    private WindowThreadPool threadPool;
    private WindowPool<String> windowPool;
    private WindowShowManager.CommandWrapper commandWrapper;
    private WindowObserverManager<String> windowManager;
    private final FlyweightWindowFactory windowFactory = new FlyweightWindowFactory();
    MyTemplateWindow myWindow;
    private static final String TAG = MainActivity.class.getName();
    private static final int REQUEST_PERMISSION_CODE = 100;
    private static String[] PERMISSIONS = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          //initView();
        // initCallClear();
        initWindowCheckOut();
        //  initSingleWindow();
        //initFactory();
        //initWindowAdapter();
        //initWindowProxy();
        //initDecorator();
        //initState();
        //initWindowComponent();
        //initVisitor();
        //initThread();
        //initCommond();
        //initWindowObserver();
        //initStrategyWindow();
        //initFlyWeightWindow();
        // initTemplateWindow();
        // initCustomFactory();
        // 检查并请求权限
        if (checkPermissions()) {
            // 已经有权限，执行文件读写操作
            performFileOperations();
        } else {
            // 请求权限
            requestPermission();
        }
        initTest();
    }

    private void sendLocalBroadCast() {
        Intent intent = new Intent();
        intent.putExtra("info","zhangSan");
        // 设置广播的action，相当于广播的名称
        String action = "cn.com.hello";
        intent.setAction(action);
        // 发送广播，广播会发送到信息中心，由信息中心负责找到这个广播的订阅者并将广播的意图传过去
        // 无序广播
        sendBroadcast(intent);
        startActivity(new Intent(MainActivity.this, TestActivity.class));
    }

    private boolean checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            PERMISSIONS = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
            for (String permission : PERMISSIONS) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        } else {
            for (String permission : PERMISSIONS) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            PERMISSIONS = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_CODE);
        } else {
            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_CODE);
        }
    }

    private void performFileOperations() {
        MyApp.getInstance().initMMKV();
       // MMKVUtils.getInstance().init(this);
        // 执行文件读写操作
        initMMKVData();
    }

    private void initTest() {
        TextView textView = findViewById(R.id.tvTest);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 读取数据
                String value1 = MMKVUtils.getInstance().decodeString("key1");
                String value2 = MMKVUtils.getInstance().decodeString("key2");
                Log.d(TAG, "====数据为===" + value1 + value2);
                textView.setText(value1 + value2);
                sendLocalBroadCast();
            }
        });
    }

    private void initMMKVData() {
        // 存储数据
        MMKVUtils.getInstance().encode("key1", "value1");
        MMKVUtils.getInstance().encode("key2", "456");
    }

    private void initCustomFactory() {
        CustomWindowFactory factory = new CustomWindowFactory(R.layout.my_window_layout);
        Window window = factory.createWindow(this);
        window.setSize(500, 500);
        window.show();
    }

    private void initTemplateWindow() {
        myWindow = new MyTemplateWindow(this);
        myWindow.setFullScreen(true);
        myWindow.setTitleBar(false);
        myWindow.setSize(400, 400);
        myWindow.setGravity(Gravity.CENTER);
        myWindow.addView(LayoutInflater.from(this).inflate(R.layout.my_window_layout, null));
        myWindow.show();
    }


    private void initFlyWeightWindow() {
        FlyweightWindow window = windowFactory.getWindow("tag");
        // 设置窗口属性
        window.setFullScreen(true);
        window.setTitleBar(false);
        window.setSize(300, 300);
        window.setGravity(Gravity.CENTER);
        window.setContentView(LayoutInflater.from(this).inflate(R.layout.my_window_layout, null));
        // 显示窗口
        window.show(this);
    }

    private void initStrategyWindow() {
        WindowStrategyBuilder<String> builder = new WindowStrategyBuilder<>(this, new FullScreenWindowStrategy());
        StrategyWindow<String> window = builder
                .setContentView(LayoutInflater.from(this).inflate(R.layout.my_window_layout, null))
                .setFullScreen(true)
                .setSize(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT)
                .setGravity(Gravity.CENTER)
                .setData("Hello, World!")
                .build();
        window.show();
    }

    private void initWindowObserver() {
        windowManager = new WindowObserverManager<>(this);
        View view = LayoutInflater.from(this).inflate(R.layout.my_window_layout, null);
        TextView textView = view.findViewById(R.id.text_view);
        Window<String> window = windowManager.createWindow(view, "Hello, world!");
        textView.setText(window.getData());
    }

    private void initCommond() {
        WindowShowManager<String> windowShowManager = new WindowShowManager<>(this);
        View view = LayoutInflater.from(this).inflate(R.layout.my_window_layout, null);
        TextView textView = view.findViewById(R.id.text_view);

        commandWrapper = windowShowManager.createWindow(view, "Hello, world!");
        windowShowManager.execute(commandWrapper);

        textView.setText(windowShowManager.getData());
    }

    private void initThread() {
        View view = LayoutInflater.from(this).inflate(R.layout.my_window_layout, null);
        TextView textView = view.findViewById(R.id.text_view);
        threadPool = new WindowThreadPool();
        windowPool = new WindowPool<>(MainActivity.this);
        windowPool.addView(view);
        windowPool.setData("Hello, world!");
        windowPool.setSize(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        windowPool.show(threadPool);
        textView.setText(windowPool.data);
    }

    private void initVisitor() {
        View view = LayoutInflater.from(this).inflate(R.layout.my_window_layout, null);
        TextView textView = view.findViewById(R.id.text_view);

        window = new WindowVisitor<>(this);
        window.addView(view);
        window.setData("Hello World");
        visitor = new WindowVisitorImpl();
        window.accept(visitor);
    }

    private void initWindowComponent() {
        TextView textView = new TextView(this);
        textView.setText("测试组合模式window");
        textView.setTextSize(20);
        textView.setTextColor(Color.WHITE);
        textView.setGravity(Gravity.CENTER);
        WindowComposite window = new WindowComposite();
        WindowCustomComponent<Object> windowLeaf = new WindowCustomComponent<>(this);
        window.add(windowLeaf);
        windowLeaf.setSize(500, 500);
        windowLeaf.setPosition(100, 100);
        windowLeaf.setGravity(Gravity.CENTER);
        windowLeaf.setData("测试数据");
        windowLeaf.addView(textView);
        window.show();
    }

    private void initState() {

    }

    private void initDecorator() {
        Window<String> window = new WindowDecorator<>(this);
        window.setData("Hello, world!");
        window.addView(LayoutInflater.from(this).inflate(R.layout.my_window_layout, null));
        window.show();
    }

    private void initWindowProxy() {
        Window<String> window = new WindowProxy<>(this);
        window.setFullScreen(true);
        window.setTitleBar(false);
        window.setSize(500, 500);
        window.setPosition(0, 0);
        window.setGravity(Gravity.CENTER);
        window.addView(LayoutInflater.from(this).inflate(R.layout.my_window_layout, null));
        window.setData("Hello, world!");
        window.show();
    }

    private void initWindowAdapter() {
        WindowAdapter<String> adapter = new WindowBuilderAdapter<>(new WindowBuilder<String>(this)
                .setContentView(R.layout.window_check_out)
                .setSize(WindowManager.LayoutParams.WRAP_CONTENT, 400));
        Window<String> window = adapter.createWindow(this);
        adapter.configureWindow(window);
        adapter.setData(window, "Hello, world!");
        window.show();
    }

    private void initFactory() {
        CheckOutBean checkOutBean = new CheckOutBean();
        checkOutBean.setTitle("选择退房");
        checkOutBean.setRoomId("181");
        checkOutBean.setOrderId("1111");
        WindowFactory<CheckOutBean> window =
                WindowFactory.create(this,
                        new WindowFactoryBuilder(this)
                                .setContentView(R.layout.window_check_out)
                                .setGravity(Gravity.RIGHT)
                                .setSize(WindowManager.LayoutParams.WRAP_CONTENT, 600)
                                .setData(checkOutBean));
        window.show();
    }

    private void initSingleWindow() {
        // 创建一个TextView并设置其属性
        TextView textView = new TextView(this);
        textView.setText("Hello, World!");
        textView.setTextSize(20);
        textView.setTextColor(Color.WHITE);
        WindowSingle window = WindowSingle.getInstance(this);
        window.setFullScreen(false);
        window.setSize(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        window.setPosition(100, 100);
        window.setGravity(Gravity.TOP | Gravity.START);
        window.addView(textView);
        window.show();
    }

    private void initWindowCheckOut() {
        CheckOutBean checkOutBean = new CheckOutBean();
        checkOutBean.setTitle("选择退房");
        checkOutBean.setRoomId("181");
        checkOutBean.setOrderId("1111ihfdsufshdjk");
        // 创建 CheckOut 窗口
        Window windowCheckOut = WindowCreate.createCheckOutWindow(this, R.layout.window_check_out, checkOutBean);
        windowCheckOut.show();
        Button btnSure = windowCheckOut.contentView.findViewById(R.id.btn_leave_sure);
        Button btnCancel = windowCheckOut.contentView.findViewById(R.id.btn_leave_cancel);
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                windowCheckOut.hide();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                windowCheckOut.hide();
            }
        });
        windows.add(windowCheckOut);
    }

    private void initView() {

 /*       // 创建并配置 Window 对象
        window = new WindowBuilder(this)
                .setContentView(R.layout.window_layout)
                .setFullScreen(true)
                .setTitleBar(false)
                .setGravity(Gravity.RIGHT)
                .setSize(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.MATCH_PARENT)
                .build(this);
        // 显示窗口
        window.show();*/
/*        TextView textView = new TextView(this);
        textView.setText("Hello, World!");
        textView.setTextSize(20);
        textView.setTextColor(Color.WHITE);

// 创建WindowManagerHelper实例
        WindowManagerHelper windowManagerHelper = WindowManagerHelper.getInstance(this);

// 设置TextView的布局参数
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                        WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.CENTER;

// 添加TextView到Window中
        windowManagerHelper.addView(textView, params);*/

        // 创建一个TextView并设置其属性
        TextView textView = new TextView(this);
        textView.setText("Float, Window!");
        textView.setTextSize(20);
        textView.setTextColor(Color.WHITE);

        // 创建FloatingWindow实例
        FloatingWindow floatingWindow = new FloatingWindow(this);

        // 设置Window的属性
        floatingWindow.setFullScreen(false);
        floatingWindow.setTitleBar(true);
        floatingWindow.setSize(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        floatingWindow.setPosition(100, 100);
        floatingWindow.setGravity(Gravity.TOP | Gravity.START);

        // 将TextView添加到Window中
        floatingWindow.addView(textView);

        // 显示Window
        floatingWindow.show();
    }


    private void initCallClear() {
        // 创建 CallClean 窗口
        CallCleanBean callCleanBean = new CallCleanBean();
        callCleanBean.setTitle("呼叫打扫");
        callCleanBean.setRoomId("182");
        Window windowCallClean = WindowCreate.createCallCleanWindow(this, R.layout.window_call_clear, callCleanBean);
        windowCallClean.show();
        windows.add(windowCallClean);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }
            if (allPermissionsGranted) {
                // 权限已授予，执行文件读写操作
                performFileOperations();
            } else {
                // 权限被拒绝，处理权限请求失败的情况
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭所有窗口
        for (Window window : windows) {
            if (window != null) {
                window.hide();
                window = null;
            }
            windows.clear();
        }
    }
}